package pl.bristleback.scrumtable.utils;

import org.apache.log4j.Logger;
import pl.bristleback.server.bristle.exceptions.BristleRuntimeException;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;

/**
 * //@todo class description
 * <p/>
 * Created on: 04.06.11 12:25 <br/>
 *
 * @author Paweł Machowski
 */
public class JWebSocketResource {
  private static Logger log = Logger.getLogger(JWebSocketResource.class.getName());

	private final String path;
	private ClassLoader classLoader;

  public JWebSocketResource(String path) {
    this.path = path;
    this.classLoader = getDefaultClassLoader();
  }

  public String getAbsoluteFilePath(){
    try {
      URL resourceUrl = getURL();
      File file = new File(toURI(resourceUrl).getSchemeSpecificPart());
      return file.getAbsolutePath();
    }
    catch (Exception e) {
      throw new BristleRuntimeException("Can not find jwebsocket.xml file", e);
    }
  }

  private URI toURI(URL resourceUrl) throws URISyntaxException{
    return new URI(resourceUrl.toString());
  }

  private URL getURL() throws IOException {
    URL url = null;
      url = this.classLoader.getResource(this.path);
    if (url == null) {
      throw new FileNotFoundException(
          path + " cannot be resolved to URL because it does not exist");
    }
    return url;
  }


    private  ClassLoader getDefaultClassLoader() {
    ClassLoader cl = null;
    try {
      cl = Thread.currentThread().getContextClassLoader();
    }
    catch (Throwable ex) {
      // Cannot access thread context ClassLoader - falling back to system class loader...
    }
    if (cl == null) {
      // No thread context class loader -> use class loader of this class.
      cl = JWebSocketResource.class.getClassLoader();
    }
    return cl;
  }
} 